package hashDemo;

import entity.Person;

import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.WeakHashMap;

/**
 * @author Ajie
 * @date 2022/6/23
 * @function
 */
public class WeakHashMapDemo {
    public static void main(String[] args) throws InterruptedException {
        Person person = new Person();
        Man man = new Man("zhangsan");
        WeakHashMap<Person, WeakReference<Man>> weakHashMap = new WeakHashMap<Person, WeakReference<Man>>();
        weakHashMap.put(person,new WeakReference(man));
        Man man1 = weakHashMap.get(person).get();

        System.out.println("WeakHashMapDemo:main: "+man1.toString());

        //回收
//        person = null;// key value 都不存在。 😄
        man = null;// 为什么 value 还存在？？ 单独 man=null.

        // 再进行gc，此时obj应该被回收了，那么queue里面应该有这个弱引用了
        System.gc();

        Iterator<Map.Entry<Person, WeakReference<Man>>> iterator = weakHashMap.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry<Person, WeakReference<Man>> next = iterator.next();
            System.out.println("WeakHashMapDemo:main:"+next.getKey()+"  value:"+next.getValue().get().toString());
        }

    }

    static class Man{
        String name;

        public Man(String name) {
            this.name = name;
        }

        @Override
        public String toString() {
            return "Man{" +
                    "name='" + name + '\'' +
                    '}';
        }
    }
}
